<?php
class import_model{
	static public function log_write($nns_func,$data,$log_summary,$nns_state){
		$db = nn_get_db(NL_DB_WRITE);
		$table='nns_mgtvbk_import_log';
		$import_data = "<import_assets/>";
		if($nns_func=='import_assets'){
			$import_data = $data['assets_content'];
		}elseif($nns_func=='modify_video'){
			$import_data = $data['assets_video_info'];
		}elseif($nns_func=='import_video_clip'){
			$import_data = $data['assets_clip_info'];
		}elseif($nns_func=='modify_video_clip'){
			$import_data = $data['assets_clip_info'];
		}elseif($nns_func=='import_video_file'){
			$import_data = $data['assets_file_info'];
		}
		$import_data = str_replace("\\","",$import_data);
		$dom = new DOMDocument('1.0', 'utf-8');
		$dom->loadXML($import_data);
		$xml_data=$dom->saveXML();
		$data = array(
			'nns_id'=>np_guid_rand(),	 
			'nns_func'=>$nns_func,
			'nns_import_data'=>addslashes($xml_data),
			'nns_state'=>$nns_state, 
			'nns_summary'=>$log_summary, 
			'nns_assets_id'=>$data['assets_id'], 
			'nns_assets_video_type'=>$data['assets_video_type'],	 
			'nns_assets_clip_id'=>$data['assets_clip_id'],	 
			'nns_assets_file_id'=>$data['assets_file_id'],	 
			'nns_svc_item_id'=>$data['svc_item_id'], 
			'nns_create_time'=>date('Y-m-d H:i:s'),
			'nns_org_id'=>SP_ORG_ID
		);
		nl_db_insert($db, $table, $data);
	}	

	static	public function get_log_list($filter,$start,$size){		
		$db = nn_get_db(NL_DB_READ);
		$sql="select SQL_CALC_FOUND_ROWS * from nns_mgtvbk_import_log where nns_org_id='".SP_ORG_ID."'";
		if($filter != null){
			$wh_arr = array();
			if(!empty($filter['nns_state'])){
				if($filter['nns_state']=='1'){
					$wh_arr[] = " nns_state!=0";
				}elseif($filter['nns_state']=='2'){
					$wh_arr[] = " nns_state=0";
				}
			}
			if (!empty($filter['nns_name'])) {
				$wh_arr[] = " nns_name like '%".$filter['nns_name']."%'";
			}
			if (!empty($filter['nns_assets_id'])) {
				$wh_arr[] = " nns_assets_id='".$filter['nns_assets_id']."'";
			}
			if (!empty($filter['nns_assets_clip_id'])) {
				$wh_arr[] = " nns_assets_clip_id='".$filter['nns_assets_clip_id']."' ";
			}
			if (!empty($filter['nns_assets_file_id'])) {
				$wh_arr[] = " nns_assets_file_id='".$filter['nns_assets_file_id']."' ";
			}
			
			if(!empty($filter['nns_func'])){
				$wh_arr[] = " nns_func='".$filter['nns_func']."' ";
			}			
			if(!empty($filter['day_picker_start'])){
				$wh_arr[] = " nns_create_time >='".$filter['day_picker_start']."' ";
			}
			if(!empty($filter['day_picker_end'])){
				$wh_arr[] = " nns_create_time <='".$filter['day_picker_end']."' ";
			}			
			if(!empty($wh_arr))	$sql .= " and ".implode(" and ",$wh_arr);
		}
		$sql .= " order by nns_create_time desc ";
		$sql .= " limit $start,$size";
		$data = nl_db_get_all($sql,$db);
    	$count_sql  = "SELECT FOUND_ROWS() ";
    	$rows = nl_db_get_col($count_sql,$db);
    	return array('data'=>$data,'rows'=>$rows);
	}

	static public function get_log_detail_by_id($id){
		$db = nn_get_db(NL_DB_READ);
		$sql="select nns_import_data from nns_mgtvbk_import_log where nns_id='".$id."'";
		return nl_db_get_col($sql,$db);
	}



	//自动注入

	static public function  auto_import_epg(){
		/***********
		$db = nn_get_db(NL_DB_READ);
		$num = 300;
		$sql = "select nns_id,nns_ref_id,nns_src_id,nns_action,nns_status from nns_mgtvbk_c2_task where nns_type='media' and nns_org_id='jllt' and nns_status=0 order by nns_create_time asc limit $num";
		$c2_task = nl_db_get_all($sql, $db);
		if(count($c2_task)==0){
			die('fail');
		}
		$query = array('nns_action'=>'add');
		foreach ($c2_task as $key => $value) {
			$vod_id = nl_db_get_col("select nns_vod_id from nns_vod_index where nns_id='{$value['nns_src_id']}'", $db);
			if(empty($vod_id)){
				continue;
			}
			$sql = "select nns_id,nns_action from nns_mgtvbk_c2_task where nns_type='vod' and nns_org_id='jllt' and nns_ref_id='{$vod_id}'";
			$c2_task_vod = nl_db_get_one($sql, $db);
			if(is_array($c2_task_vod)&&!empty($c2_task_vod)){
				//先执行主媒体注入
				if($c2_task_vod['nns_action']!='destroy'){
					$c2_task_vod['nns_action'] = 'add';
				}
				$re_vod = self::import_asset($c2_task_vod['nns_id'],$c2_task_vod['nns_action']);
				if($re_vod){
					//注入分集
					$sql = "select nns_id,nns_action from nns_mgtvbk_c2_task where nns_type='index' and nns_org_id='jllt' and nns_src_id='{$vod_id}' and nns_ref_id='{$value['nns_src_id']}'";
					$c2_task_index = nl_db_get_one($sql, $db);
					if(is_array($c2_task_index)&&!empty($c2_task_index)){
						if($c2_task_index['nns_action']!='destroy'){
							$c2_task_index['nns_action'] = 'add';
						}
						$re_index = self::import_clip($c2_task_index['nns_id'],$c2_task_index['nns_action']);
						if($re_index){
							if($value['nns_action']!='destroy'){
								$value['nns_action'] = 'add';
							}
							$re_vod_media = self::import_file($value['nns_id'],$value['nns_action']);
						}
					}
				}
			}
		}***/
	}



	/**
	 * @下发epg 
	 */
	static public function import_epg($query){
		$db = nn_get_db(NL_DB_READ);
		if(empty($query)){
			return false;
		}
		$nns_id = array_filter(explode(',', $query['nns_id']));
		
		$re = false;
		foreach ($nns_id as  $id) {
			$sql="select nns_type from nns_mgtvbk_c2_task where nns_id='$id'";
			$info = nl_db_get_one($sql, $db);
			if(empty($info)){
				continue;
			}
			if($info['nns_type']=='vod'){
				$re = self::import_asset($id,$query['nns_action']);
			}elseif($info['nns_type']=='index'){
				$re = self::import_clip($id,$query['nns_action']);
			}elseif($info['nns_type']=='media'){
				$re = self::import_file($id,$query['nns_action']);
			}else{
				continue;
			}
		}
		return $re;
	}


	static public function import_file($nns_id,$action_epg=null){
		include_once dirname(dirname(__FILE__)) . '/import/import.class.php';
		$db_r = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);
		$url = IMPROT_EPG_URL;
		$log = IMPROT_EPG_LOG;
		$import_obj = new import($url, $log);
		$action = 'add';
		if(!empty($action_epg)){
			$action = $action_epg;
		}		
		$sql = "select * from nns_mgtvbk_c2_task where nns_id='$nns_id'";
		$c2_task_info = nl_db_get_one($sql, $db_r);
		if(empty($c2_task_info)){
			return false;
		}
		if($c2_task_info['nns_type']!='media'){
			return false;
		}
		$sp_id = $c2_task_info['nns_org_id'];
		$sql = "select * from nns_vod_media where nns_id='{$c2_task_info['nns_ref_id']}' and nns_deleted!=1";
		$info = nl_db_get_one($sql, $db_r);
		
		if(empty($info)){
			$sql = "update  nns_mgtvbk_c2_task set nns_status=99,nns_action='destroy',nns_modify_time=now() where nns_org_id='$sp_id' and nns_type='media' and nns_ref_id='{$c2_task_info['nns_ref_id']}'";
			nl_execute_by_db($sql, $db_w);
			$result = $import_obj -> delete_video_file($c2_task_info['nns_ref_id']);
			return true;
			//$action == 'destroy';
		}
		
		error_log($action."\r\n",3,$log.'/'.date('Ymd').'.txt');
		if ($action == 'destroy') {
			$result = $import_obj -> delete_video_file($c2_task_info['nns_ref_id']);
			$xml="";
		} else {
		
			$xml = '<media file_id="' . $info['nns_id'] . '" file_type="' . $info['nns_filetype'] . '" ';
			$xml .= 'file_path="' . $info['nns_url'] . '" file_definition="' . $info['nns_mode'] . '" ';
			$xml .= 'file_resolution="" file_size="" file_bit_rate="' . $info['nns_kbps'] . '" file_desc="" ';
			$xml .= 'original_id="'.$info['nns_import_id'].'" ';
			//if(empty($info['nns_ex_url'])){
			//	$info['nns_ex_url'] = 'download/index/'.$info['nns_id'].'.ts';
			//}
			//$xml .= 'ex_url="'.$info['nns_ex_url'].'" ';
			if ($info['nns_dimensions'] == '0') {
				$xml .= 'file_3d="0" file_3d_type=""></media>';
			} elseif ($info['nns_dimensions'] == '100001') {
				$xml .= 'file_3d="1" file_3d_type="0"></media>';
			} elseif ($info['nns_dimensions'] == '100002') {
				$xml .= 'file_3d="1" file_3d_type="1"></media>';
			}

			$result = $import_obj -> import_video_file($info['nns_vod_id'], $info['nns_vod_index_id'], $info['nns_id'], $xml);
		}
		error_log("nns_vod_id=".$info['nns_vod_id']."\r\n",3,$log.'/'.date('Ymd').'.txt');
		error_log("nns_vod_index_id=".$info['nns_vod_index_id']."\r\n",3,$log.'/'.date('Ymd').'.txt');
		error_log("nns_id=".$info['nns_id']."\r\n",3,$log.'/'.date('Ymd').'.txt');
		error_log($xml."\r\n",3,$log.'/'.date('Ymd').'.txt');
		$re = json_decode($result, true);
		error_log(var_export($re,true)."\r\n",3,$log.'/'.date('Ymd').'.txt');
		error_log("++++++by hand++++media+++++++++++by hand++++media+++++++++++++++++++++++++++by hand++++media++++++++++++++++++"."\r\n",3,$log.'/'.date('Ymd').'.txt');
		$set = "";
			if($action == 'destroy'){
				$set = ",nns_status='destroy'";
			}
		if ($re['ret'] == '0') {
			$sql = "update nns_mgtvbk_c2_task set nns_status=99,nns_modify_time=now() $set where nns_id='{$c2_task_info['nns_id']}'";
			nl_execute_by_db($sql, $db_w);
			$log_data = array(
				'nns_id' => np_guid_rand('media'),
				'nns_video_id' => $info['nns_id'],
				'nns_video_type' => 'media', 
				'nns_org_id' => $sp_id,
				'nns_create_time'=>date('Y-m-d H:i:s'),
				'nns_action'=>$action,
				'nns_status'=>$re['ret'],
				'nns_reason'=>$re['reason'],
				'nns_data'=>$xml,
				'nns_name'=>$c2_task_info['nns_name'],
			);
			nl_db_insert($db_w, 'nns_mgtvbk_import_epg_log', $log_data);
			return true;
		}else{
			return false;
		}		
	}
	
	
	static public function import_clip($nns_id,$action_epg=null){
		include_once dirname(dirname(__FILE__)) . '/import/import.class.php';
		$db_r = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);
		$url = IMPROT_EPG_URL;
		$log = IMPROT_EPG_LOG;
		$import_obj = new import($url, $log);
		$action = 'add';
		if(!empty($action_epg)){
			$action = $action_epg;
		}
		$sql = "select * from nns_mgtvbk_c2_task where nns_id='$nns_id'";
		$c2_task_info = nl_db_get_one($sql, $db_r);
		if(empty($c2_task_info)){
			return false;
		}
		if($c2_task_info['nns_type']!='index'){
			return false;
		}
		$sp_id = $c2_task_info['nns_org_id'];
		$sql = "select * from nns_vod_index where nns_id='{$c2_task_info['nns_ref_id']}'  and nns_deleted!=1";
		
		$info = nl_db_get_one($sql, $db_r);
		if(empty($info)){
			$sql = "update nns_mgtvbk_c2_task set nns_status=99,nns_action='destroy' where nns_org_id='$sp_id' and nns_type='index' and nns_ref_id='{$c2_task_info['nns_ref_id']}'";
			nl_execute_by_db($sql, $db_w);
			$result = $import_obj -> delete_video_clip($c2_task_info['nns_ref_id']);
			return true;
			//$action == 'destroy';
		}
		
		error_log($action."\r\n",3,$log.'/'.date('Ymd').'.txt');
		if ($action == 'destroy') {
			$result = $import_obj -> delete_video_clip($c2_task_info['nns_ref_id']);
			$xml="";
		} else {		
		
			$xml = '<index clip_id="' . $info['nns_id'] . '" ';
			$xml .= 'name="' . $info['nns_name'] . '" ';
			$xml .= 'index="' . $info['nns_index'] . '" ';
			$xml .= 'time_len="' . $info['nns_time_len'] . '" ';
			$xml .= 'summary="' . $info['nns_summary'] . '" ';
			$xml .= 'pic="' . $info['nns_image'] . '" ';
			$xml .= 'director="' . str_replace("/", ",", $info['nns_director']) . '" ';
			$xml .= 'player="' . str_replace("/", ",", $info['nns_actor']) . '" ';
			$xml .= 'total_clicks="' . $info['nns_play_count'] . '" ';
			$xml .= 'release_time="' . $info['nns_create_time'] . '" ';
			$xml .= 'update_time="' . $info['nns_modify_time'] . '" ';
			$xml .= 'month_clicks="" ';
			$xml .= 'week_clicks="" ';
			$xml .= 'day_clicks="" ';
			$xml .= 'original_id="'.$info['nns_import_id'].'" ';
			$xml .= '></index>';
		

			$result = $import_obj -> import_video_clip($info['nns_vod_id'], $info['nns_id'], $xml);
			error_log("nns_vod_id=".$info['nns_vod_id']."\r\n",3,$log.'/'.date('Ymd').'.txt');
			error_log("nns_id=".$info['nns_id']."\r\n",3,$log.'/'.date('Ymd').'.txt');
			error_log($xml."\r\n",3,$log.'/'.date('Ymd').'.txt');
		}
		$re = json_decode($result, true);
		error_log(var_export($re,true)."\r\n",3,$log.'/'.date('Ymd').'.txt');
		error_log("----by hand++++index---------------------by hand++++index---------------------------------------"."\r\n",3,$log.'/'.date('Ymd').'.txt');
		$set = "";
			if($action == 'destroy'){
				$set = ",nns_status='destroy'";
			}
		if ($re['ret'] == '0') {
			$sql = "update nns_mgtvbk_c2_task set nns_status=99,nns_modify_time=now() $set where nns_id='{$c2_task_info['nns_id']}'";
			nl_execute_by_db($sql, $db_w);
			$log_data = array(
				'nns_id' => np_guid_rand('index'),
				'nns_video_id' => $info['nns_id'],
				'nns_video_type' => 'index', 
				'nns_org_id' => $sp_id,
				'nns_create_time'=>date('Y-m-d H:i:s'),
				'nns_action'=>$action,
				'nns_status'=>$re['ret'],
				'nns_reason'=>$re['reason'],
				'nns_data'=>$xml,
				'nns_name'=>$c2_task_info['nns_name'],
			);
			nl_db_insert($db_w, 'nns_mgtvbk_import_epg_log', $log_data);
			return true;
		}else{
			return false;
		}
	}
	

	//媒资ID   注入媒资
	static public function import_asset($nns_id,$action_epg=null){
		include_once dirname(dirname(__FILE__)) . '/import/import.class.php';	
		$db_r = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);
		$url = IMPROT_EPG_URL;
		$log = IMPROT_EPG_LOG;
		$import_obj = new import($url, $log);
		$action = 'add';
		if(!empty($action_epg)){
			$action = $action_epg;
		}		
		$sql = "select * from nns_mgtvbk_c2_task where nns_id='$nns_id'";
		$c2_task_info = nl_db_get_one($sql, $db_r);
		if(empty($c2_task_info)){
			return false;
		}
		if($c2_task_info['nns_type']!='vod'){
			return false;
		}
		$sp_id = $c2_task_info['nns_org_id'];
		$sql = "select * from nns_vod where nns_id='{$c2_task_info['nns_ref_id']}' and nns_deleted!=1";
		$info = nl_db_get_one($sql, $db_r);
		if(empty($info)){
			$sql = "update nns_mgtvbk_c2_task set nns_status=99,nns_action='destroy' where nns_org_id='$sp_id' and nns_type='vod' and nns_ref_id='{$c2_task_info['nns_ref_id']}'";
			nl_execute_by_db($sql, $db_w);
			$result = $import_obj -> delete_assets($c2_task_info['nns_ref_id']);
			return true;
			//$action == 'destroy';
		}	
		error_log($action."\r\n",3,$log.'/'.date('Ymd').'.txt');
		//媒资注入
		if ($action == 'destroy') {
			$result = $import_obj -> delete_assets($c2_task_info['nns_ref_id']);
			$xml = "";
		} else {				
			$xml = '<video assets_id="' . $info['nns_id'] . '" ';
			$sql = "select * from nns_depot where nns_id='{$info['nns_depot_id']}'";
			$depot = nl_db_get_one($sql, $db_r);
			$nns_asset_import_id = $info['nns_asset_import_id'];
			$sql = "SELECT * FROM `nns_vod_ex` where nns_vod_id='{$nns_asset_import_id}'";
			$vod_ex = nl_db_get_all($sql, $db_r);
			$category_name = '';
			$dom = new DOMDocument('1.0', 'utf-8');
			$depot_info = $depot['nns_category'];
			$nns_category_id = $info['nns_category_id'];
			$dom -> loadXML($depot_info);
			$categorys = $dom -> getElementsByTagName('category');
			foreach ($categorys as $category) {
				if ($category -> getAttribute('id') == (int)$nns_category_id) {
					$category_name = $category -> getAttribute('name');
					break;
				}
			}		
			$xml .= 'assets_category="' . $category_name . '" video_type="0" ';
			$xml .= 'name="' . $info['nns_name'] . '" ';
			$xml .= 'sreach_key="' . str_replace("/", ",", $info['nns_keyword']) . '" ';
			$xml .= 'view_type="' . $info['nns_view_type'] . '" ';
			$xml .= 'director="' . str_replace("/", ",", $info['nns_director']) . '" ';
			$xml .= 'player="' . str_replace("/", ",", $info['nns_actor']) . '" ';
			$xml .= 'tag="' . str_replace("/", ",", $info['nns_kind']) . '" ';
			$xml .= 'region="' . str_replace("/", ",", $info['nns_area']) . '" ';
			$xml .= 'release_time="' . $info['nns_show_time'] . '" ';
			$xml .= 'totalnum="' . $info['nns_all_index'] . '" ';
			foreach ($vod_ex as $value) {
				$xml .= $value['nns_key'] . '="' . $value['nns_value'] . '" ';
			}
			$xml .= 'smallpic="' . $info['nns_image2'] . '" ';
			$xml .= 'bigpic="' . $info['nns_image0'] . '" ';
			$xml .= 'intro="' . $info['nns_summary'] . '" ';
			$xml .= 'producer="' . str_replace("/", ",", $info['nns_producer']) . '" ';
			$xml .= 'play_role="' . $info['nns_play_role'] . '" ';
			$xml .= 'subordinate_name="' . str_replace("/", ",", $info['nns_alias_name']) . '" ';
			$xml .= 'english_name="' . str_replace("/", ",", $info['nns_eng_name']) . '" ';
			$xml .= 'language="' . str_replace("/", ",", $info['nns_language']) . '" ';
			$xml .= 'caption_language="' . str_replace("/", ",", $info['nns_text_lang']) . '" ';
			$xml .= 'copyright_range="' . str_replace("/", ",", $info['nns_remark']) . '" ';
			$xml .= 'copyright="' . str_replace("/", ",", $info['nns_copyright']) . '" ';
			$xml .= 'total_clicks="' . $info['nns_play_count'] . '" ';
			$xml .= 'day_clicks="0" ';
			$xml .= 'original_id="'.$info['nns_asset_import_id'].'" ';
			$xml .= '></video>';

			$result = $import_obj -> import_assets($xml);
			error_log($xml."\r\n",3,$log.'/'.date('Ymd').'.txt');
		}		
		$re = json_decode($result, true);
		error_log(var_export($re,true)."\r\n",3,$log.'/'.date('Ymd').'.txt');
		error_log("======by hand++++vod-============by hand++++index-================by hand++++index-================"."\r\n",3,$log.'/'.date('Ymd').'.txt');
		
		$set = "";
			if($action == 'destroy'){
				$set = ",nns_status='destroy'";
			}
		if ($re['ret'] == '0') {
			$sql = "update nns_mgtvbk_c2_task set nns_status=99,nns_modify_time=now() $set where nns_id='{$c2_task_info['nns_id']}'";
			nl_execute_by_db($sql, $db_w);
			$log_data = array(
				'nns_id' => np_guid_rand('vod'),
				'nns_video_id' => $info['nns_id'],
				'nns_video_type' => 'vod', 
				'nns_org_id' => $sp_id,
				'nns_create_time'=>date('Y-m-d H:i:s'),
				'nns_action'=>$action,
				'nns_status'=>$re['ret'],
				'nns_reason'=>$re['reason'],
				'nns_data'=>$xml,
				'nns_name'=>$c2_task_info['nns_name'],
			);
			nl_db_insert($db_w, 'nns_mgtvbk_import_epg_log', $log_data);
			return true;
		}
		return false;
	}
}
?>